package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/*****
 * 文件上传和下载
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;

    /*****
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info("上传文件名:{}", file.getOriginalFilename());
        //1.获取文件名称
        String originalFilename = file.getOriginalFilename();
        //2.获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.生成随机文件名
        String fileName = UUID.randomUUID().toString();
        //4.判断目录是否存在
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        log.info("生成的文件名为 : {}", fileName + suffix);
        try {
            file.transferTo(new File(path + fileName + suffix));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName + suffix);  // 将文件名返还给前段
    }

    /****
     * 图片下载
     * @param response
     * @param name
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) {
        FileInputStream fis = null;
        ServletOutputStream os = null;
        try {
            //1.将文件读取到内存中
            fis = new FileInputStream(path + name);

            //2.获取输出流,写会到客户端
            os = response.getOutputStream();

        /*    BufferedInputStream bis = new BufferedInputStream(fis);
            BufferedOutputStream bos = new BufferedOutputStream(os);*/

            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
